import _ from "lodash";
import {useEffect, useState} from "react";
import {Card, SearchBar, InfiniteScroll} from "antd-mobile";
import {apiFindGoods} from "@/api";
import {routePath} from "@/router";
import GoodsLine from "@/components/Goods/Line";
import {useNav, useScrollData} from "@/hooks";
import {Container, Icon} from "@/components/public";
import PlatformTabs from "@/components/PlatformTabs";
import "./searchGoods.less";

function SearchGoods() {
    const {handleNav, params} = useNav(["title"]);

    const [search, setSearch] = useState("");

    const {data, over, handleResetRefresh, bottomRefresh} = useScrollData(
        {
            params: {q: search},
            fetch: apiFindGoods,
        },
        [search]
    );

    const loadMore = async () => bottomRefresh();

    const handleDetail = () => {
        handleNav(routePath.goodsDetail, {id: "POGG9wGS3t67Jkm5ZosYBrtPt6-NgDrpBJI2Qr5R5JeCpy"});
    };

    useEffect(() => {
        if (!_.isEmpty(params)) {
            setSearch(params.title);
        }
    }, [params]);

    return (
        <Container
            className="search-goods-page"
            backArrow={<Icon className="icon-left" />}
            sticky={true}
            onRefresh={handleResetRefresh}
            title={
                search && (
                    <SearchBar
                        icon=""
                        clearable
                        onlyShowClearWhenFocus={true}
                        defaultValue={search}
                        onSearch={setSearch}
                        className="search-bar"
                        placeholder="请输入商品名称或粘贴宝贝标题"
                    />
                )
            }
            bottom={<PlatformTabs className="tabs" />}
        >
            <div className="card-wrapper">
                <Card>
                    <GoodsLine onGoDetail={handleDetail} data={data} />
                    <InfiniteScroll loadMore={loadMore} hasMore={over} />
                </Card>
            </div>
        </Container>
    );
}

export default SearchGoods;
